package com.zjoin.study.arithmetic.基础;

/**
 * 类名 AutoInteger
 * 描述
 *
 * @Author yangxw
 * @Date 2020/4/3 13:10
 * @Version 1.0
 **/
public class AutoInteger {
    public static  int atoi(String str) {
        //去除空白字符
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        //判断首字母是否为数字或者符号
        if (!Character.isDigit(str.charAt(0))
                && str.charAt(0) != '-' && str.charAt(0) != '+') {
            return 0;
        }
        long ans = 0L;
        //获取原始整数正负
        boolean neg = str.charAt(0) == '-';
        int i = !Character.isDigit(str.charAt(0)) ? 1 : 0;
        while (i < str.length() && Character.isDigit(str.charAt(i))) {
            ans = ans * 10 + (str.charAt(i++) - '0');
            //判断数字是否越界
            if (!neg && ans > Integer.MAX_VALUE) {
                ans = Integer.MAX_VALUE;
                break;
            }
            if (neg && ans > 1L + Integer.MAX_VALUE) {
                ans = 1L + Integer.MAX_VALUE;
                break;
            }
        }
        return neg ? (int) -ans : (int) ans;
    }
    
    public static void main(String[] args) {
        System.out.println(atoi(" 1234567890"));
        System.out.println(atoi("00100 "));
        System.out.println(atoi("   abc"));
        System.out.println(atoi("0001adnsdkf678"));
        System.out.println(atoi(" -2020asdf"));
    }
}
